import React, { useState } from 'react';
import { Input, Message, Form, Divider, Checkbox, Icon } from '@alifd/next';
import { useInterval } from './utils';
import loginStyles from './index.module.scss';
import loginLogo from '@/images/login_logo.png';
import { request } from 'http';
import {useHistory} from 'ice';
import {login} from '@/api/LoginAPI'
import {PAGE_URL} from '@/api/ApiUrl'
import {getCookieBBT, setCookieBBT, getBBTKey} from '@/utils/cookie';
import UserTableListPage from '@/pages/UserTableListPage';
const { Item } = Form;
const DEFAULT_DATA = {
  loginName: '',
  password: '',
  phoneNum: '',
  // autoLogin: true,
  // code: '',
};

const LoginBlock = props => {
  const { dataSource = DEFAULT_DATA } = props;
  const [postData, setValue] = useState(dataSource);
  const [isRunning, checkRunning] = useState(false);
  const [isPhone, checkPhone] = useState(false);
  const [second, setSecond] = useState(59);
  const history = useHistory();

  useInterval(
    () => {
      setSecond(second - 1);
      if (second <= 0) {
        checkRunning(false);
        setSecond(59);
      }
    },
    isRunning ? 1000 : null,
  );

  const formChange = values => {
    setValue(values);
  };

  const sendCode = (values, errors) => {
    if (errors) {
      return;
    } // get values.phone

    checkRunning(true);
  };
  /**
   * 登录提交接口
   * @date 2020-06-02
   */
  const handleSubmit = (values, errors) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    // 调用登录接口
    login(values).then((response) => {
      let data = response.data;
      if(data){
        if(data.status === 0){
          // 1 写入 cookie
          let v = response.headers[getBBTKey()];
          setCookieBBT(v)
          Message.success('登录成功')
          setTimeout(() => {
            history.push(PAGE_URL.MAIN_PAGE);
          }, 500);  
        }else{
          Message.error(data.msg)
        }
      }else{
        Message.error('登录失败!!!')
      }
    });
  };

  const phoneForm = (
    <div>
      <Item format="tel" required requiredMessage="必填" asterisk={false}>
        <Input
          name="phoneNum"
          innerBefore={
            <span className={loginStyles.innerBeforeInput}>
              +86
              <span className={loginStyles.line} />
            </span>
          }
          maxLength={20}
          placeholder="手机号"
        />
      </Item>
      <Item
        required
        requiredMessage="必填"
        style={{
          marginBottom: 0,
        }}
      >
        <Input
          name="code"
          innerAfter={
            <span className={loginStyles.innerAfterInput}>
              <span className={loginStyles.line} />
              <Form.Submit
                text
                type="primary"
                style={{
                  width: 64,
                }}
                disabled={!!isRunning}
                validate={['phone']}
                onClick={sendCode}
                className={loginStyles.sendCode}
              >
                {isRunning ? `${second}秒后再试` : '获取验证码'}
              </Form.Submit>
            </span>
          }
          maxLength={20}
          placeholder="验证码"
        />
      </Item>
    </div>
  );
  const accountForm = (
    <div>
      <Item required requiredMessage="必填">
        <Input name="loginName" maxLength={20} placeholder="用户名" />
      </Item>
      <Item
        required
        requiredMessage="必填"
        style={{
          marginBottom: 0,
        }}
      >
        <Input.Password name="password" htmlType="password" placeholder="密码" />
      </Item>
    </div>
  );

  const byAccount = () => {
    checkPhone(false);
  };

  const byForm = () => {
    checkPhone(true);
  };

  return (
    <div className={loginStyles.LoginBlock}>
      <div className={loginStyles.innerBlock}>
        <a href="#">
          <img
            className={loginStyles.logo}
            src={loginLogo}
            alt="logo"
          />
        </a>
        <div className={loginStyles.desc}>
          <span onClick={byAccount} className={isPhone?'':loginStyles.active}>
            账户密码登录
          </span>
          <Divider direction="ver" />
          <span onClick={byForm} className={isPhone?loginStyles.active:''}>
            手机号登录
          </span>
        </div>

        <Form value={postData} onChange={formChange} size="large">
          {isPhone ? phoneForm : accountForm}

          <div className={loginStyles.infoLine}>
            <Item style={{marginBottom: 0,}}>
              <Checkbox name="autoLogin" className={loginStyles.infoLeft}>自动登录</Checkbox>
            </Item>
            <a href="/" className={loginStyles.link}>忘记密码</a>
          </div>

          <Item style={{ marginBottom: 10,}}>
            <Form.Submit type="primary" onClick={handleSubmit} className={loginStyles.submitBtn} validate >
              登录
            </Form.Submit>
          </Item>
          <div className={loginStyles.infoLine}>
            {/* <Item className={styles.infoLeft}>
              其他登录方式 <Icon type="atm" size="s" /> <Icon type="atm" size="s" />{' '}
              <Icon type="atm" size="s" />
            </Item> */}
            <a href="/" className={loginStyles.link}>
              注册账号
            </a>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default LoginBlock;
